package com.ruoyi.dm.component;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import com.ruoyi.dm.domain.po.FallRecordPO;
import com.ruoyi.dm.service.IFallRecordService;
import com.ruoyi.utils.TempFallUtil;
import common.StOrbitPoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * 空间目标数据 陨落数据
 */
@Component
@Slf4j
public class FallDataStrategy implements DataStrategy<FallRecordPO> {

    @Autowired
    private IFallRecordService recordService;

    @Override
    public FallRecordPO makeupPo(FallRecordPO po) {
        //MEME_46762_STARLINK-1901_2851645_Operational_1318351548_UNCLASSIFIED.txt
        //String fileName = po.getFileName();
        //String[] split = fileName.split("_");
        ////po.setDataType(split[1]);
        //DateTime date = DateUtil.parse(split[1], "yyyy-MM-dd");
        //po.setFileDate(date);
        return po;
    }

    @Override
    public String pythonCmd(String satellite, String dataType, String filePath, String method, Integer year) {

        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(String satellite, String outFile) throws Exception {
        //输入数据,卫星轨道数据
        List<StOrbitPoint> satOrbitDataLst= new ArrayList<>();
        TempFallUtil.readStarlinkOrbitData(outFile,satOrbitDataLst);
        log.info("解析:{} size {}",outFile,satOrbitDataLst.size());
        List<FallRecordPO> list = new ArrayList<>();
        //数据太大 达蒙会报错  所以修改下精度
        for (StOrbitPoint point : satOrbitDataLst) {
            FallRecordPO build = FallRecordPO.builder().satellite(satellite).px(new BigDecimal(point.getDx()).setScale(10, RoundingMode.HALF_UP))
                    .py(new BigDecimal(point.getDy()).setScale(10, RoundingMode.HALF_UP))
                    .pz(new BigDecimal(point.getDz()).setScale(10, RoundingMode.HALF_UP))
                    .sx(new BigDecimal(point.getDvx()).setScale(10, RoundingMode.HALF_UP))
                    .sy(new BigDecimal(point.getDvy()).setScale(10, RoundingMode.HALF_UP))
                    .sz(new BigDecimal(point.getDvz()).setScale(10, RoundingMode.HALF_UP))
                    .epochTime(DateUtil.parse(point.getStrEpoch(),"yyyy-MM-dd HH:mm:ss.SSS")).build();
            list.add(build);
        }
        satOrbitDataLst = null;
        List<List<FallRecordPO>> partition = ListUtil.partition(list, 500);
        for (List<FallRecordPO> fallRecordPOS : partition) {
            recordService.saveBatch(fallRecordPOS);
        }
        try {
            //清除 重复数据
            recordService.deleteRepeat();
        }catch (Exception e) {
            log.error("",e);
        }
    }

}
